import React, { useState, useEffect, useRef } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import aiChatData from '../data/AIchat.json';
import { request } from '../api/request'


// Image preload utility
const preloadImage = (src: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    img.onload = () => resolve();
    img.onerror = () => reject();
  });
};

const AIPhotoAlbum: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate()

  const [images, setImages] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [character, setCharacter] = useState<any>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [currentImageIndex, setCurrentImageIndex] = useState<number>(0);
  const [zoomLevel, setZoomLevel] = useState<number>(1);
  const [previewLoading, setPreviewLoading] = useState<boolean>(false);
  const [showSetBgConfirm, setShowSetBgConfirm] = useState<boolean>(false);
  const [showCustomToast, setShowCustomToast] = useState<boolean>(false);
  const [toastMessage, setToastMessage] = useState<string>('');
  const [toastType, setToastType] = useState<'success' | 'error'>('success');
  const toastTimeoutRef = useRef<number | null>(null);

  // Touch gesture related states
  const startTouchDistance = useRef<number | null>(null);
  const startZoomLevel = useRef<number>(1);
  const imageRef = useRef<HTMLImageElement>(null);

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    if (toastTimeoutRef.current) {
      clearTimeout(toastTimeoutRef.current);
    }

    setToastMessage(message);
    setToastType(type);
    setShowCustomToast(true);

    toastTimeoutRef.current = window.setTimeout(() => {
      setShowCustomToast(false);
    }, 3000);
  };

  useEffect(() => {
    return () => {
      if (toastTimeoutRef.current) {
        clearTimeout(toastTimeoutRef.current);
      }
    };
  }, []);

  // 获取背景 
 useEffect(() => {
  const getAiPersonInfo = async () => {
    const response = await request.get(`/api/ai-persons/getPersonInformation`, {
      params: {
        id: id
      }
    })
    if (response.status === 200) {
      console.log('ai人设信息', response.data.data)

      // 获取到AI人设信息后，确保头像和背景已设置
      const foundCharacter = response.data.data;
      console.log('res',foundCharacter.images)
      if (foundCharacter && foundCharacter.images?.length > 0) {
        setCharacter(foundCharacter);
        setImages(foundCharacter.images);

        // Preload images
        try {
          await Promise.all(foundCharacter.images.map((img:any) => preloadImage(img)));
          console.log('All album images preloaded successfully',);
        } catch (error) {
          console.error('Error preloading album images:', error);
        }
      }
    }
    setLoading(false); 
  }
  getAiPersonInfo()
}, [id])

  // useEffect(() => {
  //   const loadCharacterImages = async () => {
  //     setLoading(true);
  //     if (id) {
  //       const foundCharacter = aiChatData.find(item => item.id === id);
  //       console.log('找到的AI人设',foundCharacter)
  //       if (foundCharacter && foundCharacter.images?.length > 0) {
  //         setCharacter(foundCharacter);
  //         setImages(foundCharacter.images);

  //         // Preload images
  //         try {
  //           await Promise.all(foundCharacter.images.map(img => preloadImage(img)));
  //           console.log('All album images preloaded successfully');
  //         } catch (error) {
  //           console.error('Error preloading album images:', error);
  //         }
  //       }
  //     }
  //     setLoading(false);
  //   };

  //   loadCharacterImages();
  // }, [id]);

  const openPreview = (imageSrc: string, index: number) => {
    setPreviewLoading(true);
    setPreviewImage(imageSrc);
    setCurrentImageIndex(index);
    setZoomLevel(1); // Reset zoom level when opening a new image
    document.body.style.overflow = 'hidden'; // Prevent scrolling when preview is open

    // Preload the image to show loading state until it's ready
    const img = new Image();
    img.src = imageSrc;
    img.onload = () => {
      setPreviewLoading(false);
    };
  };

  const closePreview = () => {
    setPreviewImage(null);
    setZoomLevel(1); // Reset zoom
    setShowSetBgConfirm(false); // Close confirmation dialog
    document.body.style.overflow = ''; // Restore scrolling
  };

  const navigateImage = (direction: 'next' | 'prev') => {
    if (images.length <= 1) return;

    setZoomLevel(1); // Reset zoom when changing images
    setPreviewLoading(true);
    setShowSetBgConfirm(false); // Close confirmation dialog when changing images

    let newIndex: number;
    if (direction === 'next') {
      newIndex = (currentImageIndex + 1) % images.length;
    } else {
      newIndex = (currentImageIndex - 1 + images.length) % images.length;
    }

    setCurrentImageIndex(newIndex);
    setPreviewImage(images[newIndex]);

    // Preload the new image
    const img = new Image();
    img.src = images[newIndex];
    img.onload = () => {
      setPreviewLoading(false);
    };
  };

  const handleZoom = (action: 'in' | 'out' | 'reset') => {
    if (action === 'in') {
      setZoomLevel(prev => Math.min(prev + 0.25, 3)); // Max zoom: 3x
    } else if (action === 'out') {
      setZoomLevel(prev => Math.max(prev - 0.25, 0.5)); // Min zoom: 0.5x
    } else {
      setZoomLevel(1); // Reset to default
    }
  };

  // Set as background image
  const setAsBackground = () => {
    if (!previewImage || !id) return;

    try {
      // Save the selected background image to localStorage
      localStorage.setItem(`bg_image_${id}`, previewImage);

      // 已将图片设置为背景
      console.log('The picture has been set as the background', previewImage);

      // 先显示成功弹窗
      showToast('The background has been set successfully!', 'success');

      // 再关闭确认对话框
      setShowSetBgConfirm(false);

      // 确保重置body的overflow样式，防止影响其他页面滚动
      document.body.style.overflow = '';

      // 减少延迟到1秒，确保用户能看到弹窗
      setTimeout(() => {
        // 再次确保导航前overflow已被重置
        document.body.style.removeProperty('overflow');
        navigate(`/ai-companion/${id}/chat`);
      }, 1000);
    } catch (error) {
      // 设置失败背景图 - 使用自定义弹窗提示失败
      console.error('Failed to set background image:', error);
      showToast('Failed to set the background image, please try again.', 'error');
      setShowSetBgConfirm(false);
      // 确保错误情况下也重置overflow
      document.body.style.overflow = '';
    }
  };

  // Handle touch gestures
  const handleTouchStart = (e: React.TouchEvent) => {
    if (e.touches.length === 2) {
      e.preventDefault();
      // Calculate distance between two fingers
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const distance = Math.hypot(
        touch2.clientX - touch1.clientX,
        touch2.clientY - touch1.clientY
      );
      startTouchDistance.current = distance;
      startZoomLevel.current = zoomLevel;
    }
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    if (e.touches.length === 2 && startTouchDistance.current !== null) {
      e.preventDefault();
      // Calculate current distance between two fingers
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const distance = Math.hypot(
        touch2.clientX - touch1.clientX,
        touch2.clientY - touch1.clientY
      );

      // Calculate scale change
      const scale = distance / startTouchDistance.current;
      const newZoomLevel = Math.max(0.5, Math.min(3, startZoomLevel.current * scale));
      setZoomLevel(newZoomLevel);
    }
  };

  const handleTouchEnd = () => {
    startTouchDistance.current = null;
  };

  // Handle keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!previewImage) return;

      switch (e.key) {
        case 'ArrowRight':
          navigateImage('next');
          break;
        case 'ArrowLeft':
          navigateImage('prev');
          break;
        case 'Escape':
          closePreview();
          break;
        case '+':
        case '=':
          handleZoom('in');
          break;
        case '-':
          handleZoom('out');
          break;
        case '0':
          handleZoom('reset');
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [previewImage, currentImageIndex, images]);

  return (
    <div className="min-h-screen bg-[#121212] text-white pb-20">
      {/* 头部导航栏 */}
      <div className="fixed top-0 left-0 right-0 z-10 flex items-center justify-between px-4 py-3 bg-[#1e1e1e] bg-opacity-95 border-b border-gray-800">
        <div className="flex items-center">
          <Link to={`/ai-companion/${id}/chat`} className="text-gray-400">
            <i className="fas fa-arrow-left"></i>
          </Link>
          <div className="flex items-center ml-4">
            {character && (
              <>
                <img
                  src={character.image}
                  alt={character.username}
                  className="w-8 h-8 rounded-full object-cover object-[center_0%]"
                />
                <span className="ml-3 font-medium text-white">{character.username}albums</span>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 自定义提示弹窗 - 修改样式使其更明显 */}
      {showCustomToast && (
        <div className="fixed top-20 left-0 right-0 flex justify-center items-center z-[9999] pointer-events-none">
          <div
            className={`px-5 py-4 rounded-lg shadow-xl text-white 
              ${toastType === 'success' ? 'bg-green-600' : 'bg-red-600'} 
              bg-opacity-95 max-w-[90%] animate-fade-in font-medium`}
          >
            <div className="flex items-center">
              <i className={`mr-3 text-xl ${toastType === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle'}`}></i>
              <span className="text-base">{toastMessage}</span>
            </div>
          </div>
        </div>
      )}

      {/* Content with padding for header */}
      <div className="pt-16 px-4">
        {loading ? (
          <div className="flex justify-center items-center h-[70vh]">
            <div className="animate-pulse flex flex-col items-center">
              <div className="w-12 h-12 border-4 border-t-pink-500 border-r-transparent border-b-pink-500 border-l-transparent rounded-full animate-spin"></div>
              <p className="mt-4 text-white opacity-80">Loading image...</p>
            </div>
          </div>
        ) : images.length > 0 ? (
          // 图片列表 
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
            {images.map((image, index) => (
              <div
                key={index}
                className="aspect-square overflow-hidden rounded-lg cursor-pointer transition-transform hover:scale-[1.02]"
                onClick={() => openPreview(image, index)}
              >
                <img
                  src={image}
                  alt={`${character?.username || 'role'} Image ${index + 1}`}
                  className="w-full h-full object-cover object-[center_0%]"
                  loading="lazy"
                />
              </div>
            ))}
          </div>
        ) : (
          <div className="flex justify-center items-center h-[70vh]">
            <div className="text-center">
              <i className="fas fa-image text-4xl text-gray-500 mb-4"></i>
              <p className="text-gray-400">No pictures were found in the album</p>
            </div>
          </div>
        )}
      </div>

      {/* Image Preview Modal */}
      {previewImage && (
        <div
          className="fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50"
          onClick={closePreview}
        >
          <div className="relative w-full h-full flex items-center justify-center">
            {/* Close button */}
            <button
              className="absolute top-4 right-4 text-white text-xl z-20 bg-black bg-opacity-50 p-2 rounded-full"
              onClick={(e) => {
                e.stopPropagation();
                setShowSetBgConfirm(true);
              }}
            >
              Set as background
            </button>

            {/* Set background confirmation dialog */}
            {showSetBgConfirm && (
              <div
                className="absolute top-16 right-4 bg-[#1e1e1e] rounded-lg shadow-lg p-4 z-30 w-60"
                onClick={(e) => e.stopPropagation()}
              >
                <p className="text-white font-medium mb-3">Set as a background image?</p>
                <div className="flex justify-end space-x-3 mt-4">
                  <button
                    className="px-3 py-1 bg-gray-700 text-white rounded-md text-sm"
                    onClick={() => setShowSetBgConfirm(false)}
                  >
                    Cancel
                  </button>
                  <button
                    className="px-3 py-1 bg-pink-600 text-white rounded-md text-sm"
                    onClick={setAsBackground}
                  >
                    Confirm
                  </button>
                </div>
              </div>
            )}

            {/* Navigation controls */}
            {images.length > 1 && (
              <>
                <button
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-black bg-opacity-50 text-white p-3 rounded-full z-20"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigateImage('prev');
                  }}
                >
                  <i className="fas fa-chevron-left"></i>
                </button>

                <button
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-black bg-opacity-50 text-white p-3 rounded-full z-20"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigateImage('next');
                  }}
                >
                  <i className="fas fa-chevron-right"></i>
                </button>
              </>
            )}

            {/* Image counter */}
            <div className="absolute top-4 left-4 bg-black bg-opacity-50 text-white px-3 py-1 rounded-full text-sm z-20">
              {currentImageIndex + 1} / {images.length}
            </div>

            {/* Loading indicator */}
            {previewLoading && (
              <div className="absolute inset-0 flex items-center justify-center z-10">
                <div className="w-12 h-12 border-4 border-t-pink-500 border-r-transparent border-b-pink-500 border-l-transparent rounded-full animate-spin"></div>
              </div>
            )}

            {/* Image */}
            <div
              className="w-full h-full flex items-center justify-center overflow-auto"
            >
              <img
                ref={imageRef}
                src={previewImage}
                alt="Preview"
                className="max-w-[90%] max-h-[90vh] object-contain transition-transform duration-200"
                style={{ transform: `scale(${zoomLevel})` }}
                onClick={(e) => {
                  e.stopPropagation();
                  closePreview();
                }}
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AIPhotoAlbum; 